package program

import (
	"fmt"
	"mi/compiler/diagnostic"
	"mi/compiler/scanner"
	"strings"
)

type FormatDiagnosticsHost interface {
	GetCurrentDirectory() string
	GetNewLine() string
}

func FormatDiagnostics(host FormatDiagnosticsHost, diagnostics ... *diagnostic.Diagnostic) string {
var output = ""
	for _, diagnostic := range diagnostics {
		if diagnostic.File != nil {
			var sourceFile = diagnostic.File
			var loc = scanner.GetFileLineAndCharacterFromPosition(sourceFile, diagnostic.Start)
			var fileName = sourceFile.Uri.Filename()
			//var relativeFileName = xpath.ConvertToRelativePath(fileName, host.GetCurrentDirectory(), func(fileName string) string {
			//	return host.GetCanonicalFileName(fileName)
			//})
			//output +=  fmt.Sprintf("%s(%d,%d): ", relativeFileName, loc.Line+1, loc.Column)
			output +=  fmt.Sprintf("%s(%d,%d): ", fileName, loc.Line+1, loc.Column)
		}

		var category = strings.ToLower(diagnostic.Category.ToString())
		output += fmt.Sprintf("%s MI%d: %s", category, diagnostic.Code, FlattenDiagnosticMessageText(diagnostic, host.GetNewLine()))
	}
	return output
}

func FlattenDiagnosticMessageText(diagnostic *diagnostic.Diagnostic, newLine string) string {
	if diagnostic.MessageChain != nil {
		var diagnosticChain = diagnostic.MessageChain
		var result = ""

		var indent = 0
		for diagnosticChain != nil {
			if indent > 0 {
				result += newLine

				for i := 0; i < indent; i++ {
					result += "  "
				}
			}
			result += diagnosticChain.MessageText
			indent++
			diagnosticChain = diagnosticChain.Next
		}

		return result
	}

	return diagnostic.MessageText
}